package conf

import (
	"fmt"
	"github.com/nacos-group/nacos-sdk-go/clients"
	"github.com/nacos-group/nacos-sdk-go/common/constant"
	"github.com/nacos-group/nacos-sdk-go/vo"
	"github.com/zxysilent/logs"
	"gopkg.in/yaml.v3"
)

var AppConf *appConf

type appConf struct {
	Server struct {
		Name string `yaml:"Name"`
		Port uint64 `yaml:"Port"`
		Addr string `yaml:"Addr"`
	} `yaml:"Server"`
	Qiniu struct {
		AccessKey string `yaml:"AccessKey"`
		SecretKey string `yaml:"SecretKey"`
		Bucket    string `yaml:"Bucket"`
		Resurl    string `yaml:"Resurl"`
	} `yaml:"Qiniu"`
	Db struct {
		Host     string `yaml:"Host"`
		Port     uint64 `yaml:"Port"`
		User     string `yaml:"User"`
		Password string `yaml:"Password"`
		DbName   string `yaml:"DbName"`
		Params   string `yaml:"Params"`
	} `yaml:"DB"`
	Nacos struct {
		Host string `yaml:"Host"`
		Port uint64 `yaml:"Port"`
	} `yaml:"Nacos"`
}

// mb4 most bytes 4
// uid:pass@tcp(host:port)/dbname?charset=utf8mb4&parseTime=true&loc=Local
// 用户名:密码@tcp(主机:端口)/数据库名称?charset=utf8mb4&parseTime=true&loc=Local
const _dsn = "%s:%s@tcp(%s:%d)/%s?%s"

// MySQL链接字符串
func (app *appConf) Dsn() string {
	path := fmt.Sprintf(_dsn, app.Db.User, app.Db.Password, app.Db.Host, app.Db.Port, app.Db.DbName, app.Db.Params)
	return path
}

func InitConf(filename string) *appConf {
	AppConf = &appConf{}
	bytes, err := Asset(filename)
	//if yamlFile, err := ioutil.ReadFile(filename); err != nil {
	//} else

	if err = yaml.Unmarshal(bytes, AppConf); err != nil {
	}
	logs.Info("配置加载完成... {}", AppConf)
	return AppConf
}

func (app *appConf) InitNacos() {
	sc := []constant.ServerConfig{
		{
			IpAddr: app.Nacos.Host,
			Port:   app.Nacos.Port,
		},
	}
	cc := constant.ClientConfig{
		NamespaceId:         "", //namespace id
		TimeoutMs:           5000,
		NotLoadCacheAtStart: true,
		LogDir:              "/tmp/nacos/log",
		CacheDir:            "/tmp/nacos/cache",
		RotateTime:          "1h",
		MaxAge:              3,
		LogLevel:            "debug",
	}
	// a more graceful way to create naming client
	namingClient, err := clients.NewNamingClient(
		vo.NacosClientParam{
			ClientConfig:  &cc,
			ServerConfigs: sc,
		},
	)

	if err != nil {
		panic(err)
	}

	_, err = namingClient.RegisterInstance(vo.RegisterInstanceParam{
		Ip:          "127.0.0.1",
		Port:        app.Server.Port,
		ServiceName: app.Server.Name,
		Weight:      10,
		Enable:      true,
		Healthy:     true,
		Ephemeral:   true,
		Metadata:    map[string]string{"idc": "shanghai"},
		//ClusterName: "cluster-a", // 默认值DEFAULT
		//GroupName:   "group-a",   // 默认值DEFAULT_GROUP
	})
	fmt.Print("nacos Inited")
}
